"""
用户认证管理后台
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User, LoginLog, Permission, RolePermission


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    """用户管理"""
    
    list_display = ['username', 'email', 'first_name', 'last_name', 'role', 'is_active', 'date_joined']
    list_filter = ['role', 'is_active', 'date_joined']
    search_fields = ['username', 'email', 'first_name', 'last_name']
    ordering = ['-date_joined']
    
    fieldsets = BaseUserAdmin.fieldsets + (
        ('扩展信息', {
            'fields': ('role', 'phone', 'avatar', 'last_login_ip')
        }),
    )
    
    add_fieldsets = BaseUserAdmin.add_fieldsets + (
        ('扩展信息', {
            'fields': ('role', 'phone', 'email', 'first_name', 'last_name')
        }),
    )


@admin.register(LoginLog)
class LoginLogAdmin(admin.ModelAdmin):
    """登录日志管理"""
    
    list_display = ['user', 'ip_address', 'login_time', 'is_success']
    list_filter = ['is_success', 'login_time']
    search_fields = ['user__username', 'ip_address']
    ordering = ['-login_time']
    readonly_fields = ['user', 'ip_address', 'user_agent', 'login_time', 'is_success', 'failure_reason']


@admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
    """权限管理"""
    
    list_display = ['name', 'codename', 'module', 'created_at']
    list_filter = ['module', 'created_at']
    search_fields = ['name', 'codename', 'description']
    ordering = ['module', 'name']


@admin.register(RolePermission)
class RolePermissionAdmin(admin.ModelAdmin):
    """角色权限管理"""
    
    list_display = ['role', 'permission', 'created_at']
    list_filter = ['role', 'permission__module', 'created_at']
    search_fields = ['permission__name', 'permission__codename']
    ordering = ['role', 'permission__module', 'permission__name']
